<script setup lang="ts">
import {onMounted, ref} from "vue";
import myAxios from "../../plugins/MyAxios.ts";
import {showFailToast, showSuccessToast} from "vant";

const currentPage = ref(1)
const pageSize = ref<number>(3)
const totalItems = ref<number>()

const onClickLeft = () => history.back();
const teamList = ref()

const getTeam = async () => {
  try {
    const result = await myAxios.post('/team/get/page', {
      thePageNum: currentPage.value,
      pageSize: pageSize.value
    })
    teamList.value = result.data.data.records;
  } catch (e) {
    showFailToast("网络异常")
    console.log(e)
  }
}

onMounted(async () => {
  try {
    const date = await myAxios.get('/team/totalCount');
    totalItems.value = date.data.data
    const result = await myAxios.post('/team/get/page', {
      thePageNum: 1,
      pageSize: pageSize.value
    })
    teamList.value = result.data.data.records;
  } catch (e) {
    showFailToast("网络异常")
    console.log(e)
  }
})

const password = ref<string>()
const teamId = ref()
const show = ref<boolean>(false)
const joinTeam = async ({id, status} : { id: number; status: number }) => {
  if (status === 2) {
    show.value = true;
    teamId.value = id
  } else {
    await joinTeamRequest(id)
  }
}

async function joinTeamRequest(id : number) {
  try {
    const result = await myAxios.post('/team/joinTeam', {
      id: id,
      password: password.value
    })
    if (result.data.code === 200) {
      showSuccessToast("成功加入队伍")
    }
  } catch (e) {
    showFailToast("加入队伍失败")
    console.log(e)
  }
}

function formatTime(time : string) {
  const date = new Date(time);
  return date.toISOString().split('T')[0];
}
</script>

<template>
  <van-nav-bar title="麦语伙伴" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div>
    <div v-for="item in teamList" :key="item.id">
      <van-swipe-cell>
        <div style="display: flex">
          <div>
            <van-image width="100" height="100" :src="item.creatUser.avatarUrl" fit="cover"></van-image>
          </div>
          <div style="margin-left: 20px">
            <h3>{{ item.name }}</h3>
            <p>当前人数 / 最大人数：{{ item.curNum }} / {{item.maxNum}}</p>
            <p>队伍过期时间：{{formatTime(item.expireTime)}}</p>
          </div>
        </div>
        <template #right>
          <van-button square type="primary" text="加入" style="height: 100%" @click="joinTeam(item)"/>
        </template>
      </van-swipe-cell>
    </div>
  </div>
  <van-pagination
      v-model="currentPage"
      :total-items="totalItems"
      :items-per-page="5"
      :show-page-size="3"
      force-ellipses
      @change="getTeam"
  />
  <van-dialog v-model:show="show" title="请输入入队密码" @confirm="joinTeamRequest(teamId)" show-cancel-button>
    <van-cell-group inset>
      <van-field v-model="password" label="密码" placeholder="请输入密码" />
    </van-cell-group>
  </van-dialog>
</template>

<style scoped>
p {
margin: 5px;
}

h3 {
  margin: 5px;
}
</style>